package cn.raven.basic.utils;

import cn.raven.basic.jwt.*;
import cn.raven.org.domain.Employee;
import cn.raven.org.domain.Shop;
import cn.raven.org.service.IEmployeeService;
import cn.raven.user.domain.Logininfo;
import cn.raven.user.domain.User;
import cn.raven.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;
import java.util.Map;

@Slf4j
public class LoginContext {

    public static Logininfo getLoginin(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token != null){
            PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getJwtRsaPubData());
            Payload<UserJwt> payload = JwtUtils.getInfoFromToken(token, publicKey, UserJwt.class);
            if (payload == null){
                log.error("payloadData is null!");
               return null;
            }
           return payload.getUserInfo().getLogininfo();
        }
        return null;
    }
    public static User getUser(HttpServletRequest request){
        //先获取spring容器
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        //获取一个map
        Map<String, IUserService> map = webApplicationContext.getBeansOfType(IUserService.class);
        //获取map里的bean
        IUserService userService = map.get("userServiceImpl");
        //根据loginin的id查询user
        User user = userService.findByLogininfoId(getLoginin(request).getId());
        return user;
    }

    public static Employee getEmployee(HttpServletRequest request){
        //先获取spring容器
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        //获取一个map
        Map<String, IEmployeeService> map = webApplicationContext.getBeansOfType(IEmployeeService.class);
        //获取map里的bean
        IEmployeeService employeeService = map.get("employeeServiceImpl");
        //employee
        Employee employee = employeeService.findByLogininfoId(getLoginin(request).getId());
        return employee;
    }
}
